package com.lagou.rocketmq.util.lock;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName DistributedRedisLock
 * @Description TODO
 * @Author xsq
 * @Date 2020/11/23 17:14
 **/
@Slf4j
@Component
public class RedisLockHandler {


    @Autowired
    private RedissonClient redissonClient;


    /**
     * 分布式加锁
     *
     * @param key
     */

    public void lock(String key) {
        try {
            RLock lock = redissonClient.getLock(key);
            //执行加锁操作,并设置10秒过期时间防止死锁
            lock.lock(10, TimeUnit.SECONDS);
            log.info("Thread [{}] DistributedRedisLock lock [{}] success", Thread.currentThread().getName(), key);
        } catch (Exception e) {
            log.error("DistributedRedisLock lock [{}] Exception:", key, e);
        }
    }


    /**
     * 分布式释放锁
     */
    public void unLock(String key) {
        try {
            RLock lock = redissonClient.getLock(key);
            //执行加锁操作,并设置10秒过期时间防止死锁
            lock.unlock();
            log.info("Thread [{}] DistributedRedisLock unlock [{}] success", Thread.currentThread().getName(), key);
        } catch (Exception e) {
            log.error("DistributedRedisLock unlock [{}] Exception:", key, e);
        }
    }

    /**
     * 获取key
     *
     * @param key
     */
    public Integer getValue(String key) {
        RBucket<Integer> bucket = redissonClient.getBucket(key);
        return bucket.get();
    }

    /**
     * 获取key
     *
     * @param key
     */
    public void setValue(String key, String value) {
        RBucket<String> bucket = redissonClient.getBucket(key);
        bucket.set(value);
    }
}
